package com.cocos.game;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustAdRevenue;
import com.adjust.sdk.AdjustConfig;

import com.android.fruitballs2048v2.explorer.BuildConfig;
import com.android.fruitballs2048v2.explorer.R;
import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxAdListener;
import com.applovin.mediation.MaxAdRevenueListener;
import com.applovin.mediation.MaxAdWaterfallInfo;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.MaxNetworkResponseInfo;
import com.applovin.mediation.MaxReward;
import com.applovin.mediation.MaxRewardedAdListener;
import com.applovin.mediation.ads.MaxInterstitialAd;
import com.applovin.mediation.ads.MaxRewardedAd;
import com.applovin.sdk.AppLovinSdk;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class BaseAdActivity extends AppActivity implements MaxAdRevenueListener {


    private static final String TAG = "Ab_BaseAdActivity";
    private static final int OVERLAY_PERMISSION_REQUEST_CODE = 1;

    private MaxRewardedAd maxRewardedAd;
    private int rewardedRetryAttempt = 0;

    private MaxInterstitialAd maxInterstitialAd;
    private int interstitialRetryAttempt = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (BuildConfig.DEBUG) {
            // 创建FAB实例
            requestOverlayPermission();
        }
        initAd();
    }

    private void requestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, OVERLAY_PERMISSION_REQUEST_CODE);
            } else {
                addDebugView();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    // Permission not granted
                    Toast.makeText(this, "Overlay permission not granted.", Toast.LENGTH_SHORT).show();
                } else {
                    // Permission granted, proceed with adding the overlay window.
                    addDebugView();
                }
            }
        }
    }

    private void addDebugView() {
        LinearLayout rootContainerLayout = new LinearLayout(this);

        LinearLayout containerLayout = new LinearLayout(this);
        containerLayout.setVisibility(View.GONE);
        Button debugBtn = new Button(this);
        debugBtn.setText("dev");// 使用你的图标
        debugBtn.setOnClickListener(v -> {
            containerLayout.setVisibility(containerLayout.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        });
        rootContainerLayout.setOrientation(LinearLayout.VERTICAL);
        rootContainerLayout.addView(debugBtn);
        rootContainerLayout.addView(containerLayout);


        Button fab = new Button(this);
        fab.setText("中介器");// 使用你的图标
        fab.setOnClickListener(v -> {
            AppLovinSdk.getInstance(this).showMediationDebugger();
        });

        containerLayout.addView(fab);
        fab = new Button(this);
        fab.setText("pop");// 使用你的图标
        fab.setOnClickListener(v -> {
            planet_AndroidClient_poof.showPop();
        });
        containerLayout.addView(fab);

        fab = new Button(this);
        fab.setText("type");// 使用你的图标
        fab.setOnClickListener(v -> {
            planet_AndroidClient_poof.planet_callNative_poof(planet_AndroidClient_poof.API_TYPE, "{\n" +
                    "    \"" + planet_AndroidClient_poof.REQUEST_TOKEN + "\": \"123\",\n" +
                    "    \"" + planet_AndroidClient_poof.REQUEST_DATA + "\": {\n" +
                    "        \"" + planet_AndroidClient_poof.DATA_TYPE + "\": \"incentive\"\n" +
                    "    }\n" +
                    "}");
        });
        containerLayout.addView(fab);

        fab = new Button(this);
        fab.setText("AD");// 使用你的图标
        fab.setOnClickListener(v -> {
            planet_AndroidClient_poof.planet_callNative_poof(planet_AndroidClient_poof.API_AD, "{\n" +
                    "    \"" + planet_AndroidClient_poof.REQUEST_TOKEN + "\": \"123\",\n" +
                    "    \"" + planet_AndroidClient_poof.REQUEST_DATA + "\": {\n" +
                    "        \"" + planet_AndroidClient_poof.API_REQUEST_DATA_AD_TYPE + "\": \"incentive\"\n" +
                    "    }\n" +
                    "}");
        });
        containerLayout.addView(fab);

        TextView textView = new TextView(this);
        StringBuilder builder = new StringBuilder();
        builder.append("DeviceId:").append(DeviceUtil.getDeviceId()).append("\n");
        Locale systemLocale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            systemLocale = MApplication.instance.getResources().getConfiguration().getLocales().get(0);
        } else {
            systemLocale = Locale.getDefault();
        }
        builder.append("LocalInfo:").append(systemLocale.getCountry()).append("  ").append(systemLocale.getLanguage());
        textView.setText(builder);
        textView.setHeight(500);
        textView.setMovementMethod(new ScrollingMovementMethod());
        fab = new Button(this);
        fab.setText("调试信息");// 使用你的图标
        fab.setOnClickListener(v -> {
            textView.setVisibility(textView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        });

        containerLayout.addView(fab);
        containerLayout.addView(textView);


        // 创建LayoutParams
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.TOP | Gravity.START;
        params.x = 50; // 调整X坐标
        params.y = 50; // 调整Y坐标

        // 添加按钮到窗口
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.addView(rootContainerLayout, params);
    }


    /**
     * 供JS调用
     */
    public void showRewardedAd() {
        if (maxRewardedAd.isReady()) {
            maxRewardedAd.showAd();
        } else {
            planet_AndroidClient_poof.onAdPlayError(AdType.Rewarded);
            maxRewardedAd.loadAd();
        }
    }

    boolean isShowPoPing = false;

    public void showPop() {
        Log.d(TAG, "showPop");
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// 加载你的布局文件
        View popupView = inflater.inflate(R.layout.pop_layout, null);

// 创建PopupWindow实例
        PopupWindow popupWindow = new PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true // 设置PopupWindow可聚焦
        );
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

// 创建一个Handler来延迟关闭PopupWindow
        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                isShowPoPing = false;
            }
        };
        isShowPoPing = true;
// 设置PopupWindow在屏幕上的位置并显示
        popupWindow.showAtLocation(
                getWindow().getDecorView(),
                Gravity.CENTER,
                0,
                0
        );

// 在PopupWindow显示后5秒执行关闭操作
        handler.postDelayed(runnable, 1500); // 延迟5000毫秒(5秒)

    }

    /**
     * 供JS调用
     */
    public void showInterstitialAd() {
        if (maxInterstitialAd.isReady()) {
            maxInterstitialAd.showAd();
        } else {
            planet_AndroidClient_poof.onAdPlayError(AdType.Interstitial);
            maxInterstitialAd.loadAd();
        }
    }

    private void initAd() {
        initRewardedAd();
        initInterstitialAd();
        if (MApplication.instance.isApplovinInitOk) {
            firstLoadAd();
            MApplication.instance.isFirstLoadAdStart = true;
        }
    }

    public void firstLoadAd() {
        maxRewardedAd.loadAd();
        maxInterstitialAd.loadAd();
    }

    private void initInterstitialAd() {
        maxInterstitialAd = new MaxInterstitialAd(MApplication.INTERSTITIAL_AD_UNIT_ID, this);
        // 2024/7/5 首次预加载、每次播放完预加载下次、加载失败重试机制
        maxInterstitialAd.setListener(new MaxAdListener() {
            @Override
            public void onAdLoaded(@NonNull MaxAd maxAd) {
                Log.d(TAG, "interstitial onAdLoaded:\n" + maxAd);
                printfLogWithLoaded(maxAd);
                interstitialRetryAttempt = 0;
            }

            @Override
            public void onAdDisplayed(@NonNull MaxAd maxAd) {
                Log.d(TAG, "interstitial onAdDisplayed:\n" + maxAd);
                maxInterstitialAd.loadAd();
                // TODO: 2024/7/8 是否需要回调JS

            }

            @Override
            public void onAdHidden(@NonNull MaxAd maxAd) {
                Log.d(TAG, "interstitial onAdHidden:\n" + maxAd);
                maxInterstitialAd.loadAd();
                MApplication.instance.initAdjust();
                planet_AndroidClient_poof.onAdPlayOver(AdType.Interstitial);
            }

            @Override
            public void onAdClicked(@NonNull MaxAd maxAd) {
                Log.d(TAG, "interstitial onAdClicked:\n" + maxAd);
            }

            @Override
            public void onAdLoadFailed(@NonNull String s, @NonNull MaxError maxError) {
                Log.d(TAG, "interstitial onAdLoadFailed:\n" + s + "\n" + maxError);
                printfLogWithLoaded(s,maxError);
                // Rewarded ad failed to load. We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds).
                // 奖励广告加载失败。我们建议使用指数级递增的延迟时间进行重试，直到达到最大延迟时间（本例中为64秒）
                interstitialRetryAttempt++;
                long delayMillis = TimeUnit.SECONDS.toMillis((long) Math.pow(2, Math.min(6, interstitialRetryAttempt)));

                new Handler().postDelayed(maxInterstitialAd::loadAd, delayMillis);
            }

            @Override
            public void onAdDisplayFailed(@NonNull MaxAd maxAd, @NonNull MaxError maxError) {
                Log.d(TAG, "interstitial onAdDisplayFailed:\n" + maxAd + "\n" + maxError);
                maxInterstitialAd.loadAd();
                planet_AndroidClient_poof.onAdPlayError(AdType.Interstitial);
            }
        });
        maxInterstitialAd.setRevenueListener(this);
    }

    private void initRewardedAd() {
        maxRewardedAd = MaxRewardedAd.getInstance(MApplication.REWARDED_AD_UNIT_ID, this);
        //  2024/7/5 首次预加载、每次播放完预加载下次、加载失败重试机制
        maxRewardedAd.setListener(new MaxRewardedAdListener() {
            @Override
            public void onUserRewarded(@NonNull MaxAd maxAd, @NonNull MaxReward maxReward) {
                Log.d(TAG, "rewarded onUserRewarded:\n" + maxAd + "\n" + maxReward);
                planet_AndroidClient_poof.onAdPlayOver(AdType.Rewarded);
                maxRewardedAd.loadAd();
            }

            @Override
            public void onAdLoaded(@NonNull MaxAd maxAd) {
                Log.d(TAG, "rewarded onAdLoaded:\n" + maxAd);
                printfLogWithLoaded(maxAd);
                rewardedRetryAttempt = 0;
            }

            @Override
            public void onAdDisplayed(@NonNull MaxAd maxAd) {
                Log.d(TAG, "rewarded onAdDisplayed:\n" + maxAd);
                maxRewardedAd.loadAd();
                // TODO: 2024/7/8 是否需要回调JS
            }

            @Override
            public void onAdHidden(@NonNull MaxAd maxAd) {
                Log.d(TAG, "rewarded onAdHidden:\n" + maxAd);
                MApplication.instance.initAdjust();
                maxRewardedAd.loadAd();
            }

            @Override
            public void onAdClicked(@NonNull MaxAd maxAd) {
                Log.d(TAG, "rewarded onAdClicked:\n" + maxAd);
            }

            @Override
            public void onAdLoadFailed(@NonNull String s, @NonNull MaxError maxError) {
                Log.d(TAG, "rewarded onAdLoadFailed:\n" + s + "\n" + maxError);
                printfLogWithLoaded(s, maxError);
                // Rewarded ad failed to load. We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds).
                // 奖励广告加载失败。我们建议使用指数级递增的延迟时间进行重试，直到达到最大延迟时间（本例中为64秒）
                rewardedRetryAttempt++;
                long delayMillis = TimeUnit.SECONDS.toMillis((long) Math.pow(2, Math.min(6, rewardedRetryAttempt)));

                new Handler().postDelayed(maxRewardedAd::loadAd, delayMillis);
            }

            @Override
            public void onAdDisplayFailed(@NonNull MaxAd maxAd, @NonNull MaxError maxError) {
                Log.d(TAG, "rewarded onAdDisplayFailed:\n" + maxAd + "\n" + maxError);
                maxRewardedAd.loadAd();
                planet_AndroidClient_poof.onAdPlayError(AdType.Rewarded);
            }
        });
        maxRewardedAd.setRevenueListener(this);
    }


    @Override
    public void onAdRevenuePaid(@NonNull MaxAd maxAd) {
        // 2024/7/5 AdJust 埋点
        AdjustAdRevenue adjustAdRevenue = new AdjustAdRevenue(AdjustConfig.AD_REVENUE_APPLOVIN_MAX);
        adjustAdRevenue.setRevenue(maxAd.getRevenue(), "USD");
        adjustAdRevenue.setAdRevenueNetwork(maxAd.getNetworkName());
        adjustAdRevenue.setAdRevenueUnit(maxAd.getAdUnitId());
        adjustAdRevenue.setAdRevenuePlacement(maxAd.getPlacement());

        Adjust.trackAdRevenue(adjustAdRevenue);
    }

    private void printfLogWithLoaded(final MaxAd ad) {
        if (BuildConfig.DEBUG) {
            MaxAdWaterfallInfo waterfall = ad.getWaterfall();
            if (waterfall == null) return;
            Log.d(TAG, "Waterfall Name: " + waterfall.getName() + " and Test Name: " + waterfall.getTestName());
            Log.d(TAG, "Waterfall latency was: " + waterfall.getLatencyMillis() + " milliseconds");

            String waterfallInfoStr;
            for (MaxNetworkResponseInfo networkResponse : waterfall.getNetworkResponses()) {
                waterfallInfoStr = "Network -> " + networkResponse.getMediatedNetwork() +
                        "\n...adLoadState: " + networkResponse.getAdLoadState() +
                        "\n...latency: " + networkResponse.getLatencyMillis() + " milliseconds" +
                        "\n...credentials: " + networkResponse.getCredentials();
                if (networkResponse.getError() != null) {
                    waterfallInfoStr += "\n...error: " + networkResponse.getError();
                }
                Log.d(TAG, waterfallInfoStr);
            }
        }
    }

    private void printfLogWithLoaded(final String adUnitId, final MaxError error) {
        MaxAdWaterfallInfo waterfall = error.getWaterfall();
        if (waterfall == null) return;
        Log.d(TAG, "Waterfall Name: " + waterfall.getName() + " and Test Name: " + waterfall.getTestName());
        Log.d(TAG, "Waterfall latency was: " + waterfall.getLatencyMillis() + " milliseconds");

        for (MaxNetworkResponseInfo networkResponse : waterfall.getNetworkResponses()) {
            Log.d(TAG, "Network -> " + networkResponse.getMediatedNetwork() +
                    "...latency: " + networkResponse.getLatencyMillis() +
                    "...credentials: " + networkResponse.getCredentials() + " milliseconds" +
                    "...error: " + networkResponse.getError());
        }
    }
}
